<template>
  <v-page
    background="#f5f6fa"
    header-background="white"
    footer-background="white"
    empty-oss-src="empty-order.png"
    empty-text="暂无订单"
    padding-top="24rpx"
    :scroll-top="scrollTop"
    :scroll-with-animation="false"
  >
    <template #header>
      <v-navbar title="计算成本" native />
    </template>
    <template #default>
      <view class="container">
        <!-- 创建新记录卡片 -->
        <view class="anime-card create-card">
          <view class="form-item">
            <text class="label">
              购入日期
            </text>
            <picker mode="date" :value="newItem.date" @change="dateChange">
              <view class="input">
                {{ newItem.date || '请选择日期' }}
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="label">
              物品名称
            </text>
            <input v-model="newItem.name" placeholder="请输入物品名称" class="input">
          </view>

          <view class="form-item">
            <text class="label">
              买入价格
            </text>
            <input
              v-model="newItem.price"
              type="number"
              placeholder="请输入价格"
              class="input"
            >
          </view>

          <view class="form-item switch-item">
            <text class="label">
              启用告警
            </text>
            <wd-switch v-model="newItem.alertEnabled" active-color="#FF6699" />
          </view>

          <view v-if="newItem.alertEnabled" class="form-item">
            <text class="label">
              告警价格
            </text>
            <input
              v-model="newItem.alarmPrice"
              type="number"
              placeholder="请输入价格"
              class="input"
            >
          </view>

          <button class="anime-button" @click="createItem">
            点击创建
          </button>
        </view>

        <!-- 统计卡片 -->
        <view class="anime-card stats-card">
          <text class="card-title">
            花费统计
          </text>
          <view class="stats-row">
            <view class="stat-item">
              <text class="stat-value">
                {{ totalDailyCost.toFixed(2) }}元
              </text>
              <text class="stat-label">
                日均花费
              </text>
            </view>
            <view class="stat-item">
              <text class="stat-value">
                {{ totalCost.toFixed(2) }}元
              </text>
              <text class="stat-label">
                总花费
              </text>
            </view>
          </view>
        </view>

        <!-- 记录列表 -->
        <view class="record-list">
          <view v-for="(item, index) in items" :key="index" class="anime-card record-item">
            <view class="item-header">
              <text class="item-name">
                {{ item.name }}
              </text>
              <text class="item-cost">
                {{ calculateDailyCost(item).toFixed(2) }}元/天
              </text>
            </view>

            <view class="item-details">
              <text>买入时间: {{ item.date }}</text>
              <text>买入价格: {{ item.price }}元</text>
              <text>至今开销: {{ calculateDailyCost(item).toFixed(2) }}元/天</text>
            </view>

            <view class="item-actions">
              <button class="anime-button small" @click="() => deleteItem(index)">
                删除
              </button>
              <button class="anime-button small" @click="() => duplicateItem(index)">
                复制
              </button>
            </view>
          </view>
        </view>
      </view>
    </template>
  </v-page>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';

interface CostItem {
  name: string;
  price: number;
  date: string;
  alertEnabled: boolean;
  alarmPrice?: number;
}
const getTodayDate = (): string => {
  const today = new Date();
  return `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
};

// 响应式数据
const newItem = ref<CostItem>({
  name: '',
  price: 0,
  date: getTodayDate(),
  alertEnabled: false,
  alarmPrice: 0,
});

const items = ref<CostItem[]>([]);

// 计算属性
const totalDailyCost = computed(() => {
  return items.value.reduce((sum, item) => sum + calculateDailyCost(item), 0);
});

const totalCost = computed(() => {
  return items.value.reduce((sum, item) => sum + item.price, 0);
});

const dateChange = (e: { detail: { value: string } }) => {
  newItem.value.date = e.detail.value;
};

const calculateDailyCost = (item: CostItem): number => {
  const purchaseDate = new Date(item.date);
  const today = new Date();
  const diffTime = today.getTime() - purchaseDate.getTime();
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

  return diffDays > 0 ? item.price / diffDays : item.price;
};

const createItem = (): void => {
  if (!newItem.value.name || !newItem.value.price) {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none',
    });
    return;
  }

  items.value.push({
    ...newItem.value,
    price: Number(newItem.value.price),
  });

  saveItems();
  resetForm();

  uni.showToast({
    title: '添加成功',
    icon: 'success',
  });
};

const deleteItem = (index: number): void => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这条记录吗？',
    success: (res) => {
      if (res.confirm) {
        items.value.splice(index, 1);
        saveItems();
      }
    },
  });
};

const scrollTop = ref<number>(0);

const duplicateItem = async (index: number) => {
  newItem.value = { ...items.value[index] };

  scrollTop.value = 1;
  await new Promise((resolve) => setTimeout(resolve, 100));
  scrollTop.value = 0;
};

const resetForm = (): void => {
  newItem.value = {
    name: '',
    price: 0,
    date: getTodayDate(),
    alertEnabled: false,
  };
};

const saveItems = (): void => {
  uni.setStorageSync('costItems', items.value);
};

const loadItems = (): void => {
  const savedItems = uni.getStorageSync('costItems');
  if (savedItems) {
    items.value = savedItems;
  }
};

// 生命周期钩子
onMounted(() => {
  loadItems();
});
</script>

<style>
/* 样式保持不变 */
page {
  background-color: #fff5f7;
  font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

.container {
  padding-top: 0;
  padding: 20rpx;
  padding-bottom: 100rpx;
}

.title {
  font-size: 40rpx;
  font-weight: bold;
  color: #ff6699;
  text-shadow: 2rpx 2rpx 4rpx rgba(255, 102, 153, 0.2);
}

.anime-card {
  background: white;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 8rpx 16rpx rgba(255, 102, 153, 0.1);
  border: 1rpx solid #ffe6ee;
  position: relative;
  overflow: hidden;
}

.create-card {
  background: linear-gradient(135deg, #fff0f5, #ffffff);
}

.stats-card {
  background: linear-gradient(135deg, #f0f8ff, #ffffff);
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
  margin-bottom: 30rpx;
  display: block;
}

.form-item {
  margin-bottom: 25rpx;
}

.label {
  display: block;
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.input {
  border: 1rpx solid #ffccdd;
  border-radius: 10rpx;
  padding: 15rpx 20rpx;
  font-size: 28rpx;
  background: #fff9fb;
  color: #333333;
}

.switch-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.anime-button {
  background: #ff6699;
  color: white;
  border-radius: 50rpx;
  font-size: 30rpx;
  margin-top: 20rpx;
  border: none;
  box-shadow: 0 4rpx 8rpx rgba(255, 102, 153, 0.3);
  transition: all 0.3s;
}

.anime-button:active {
  transform: scale(0.98);
  box-shadow: 0 2rpx 4rpx rgba(255, 102, 153, 0.3);
}

.anime-button.small {
  font-size: 26rpx;
  padding: 0 30rpx;
  height: 60rpx;
  line-height: 60rpx;
  display: inline-block;
  margin: 0 10rpx;
}

.stats-row {
  display: flex;
  justify-content: space-around;
}

.stat-item {
  text-align: center;
  padding: 20rpx;
}

.stat-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #ff6699;
  display: block;
}

.stat-label {
  font-size: 24rpx;
  color: #999;
  display: block;
}

.record-item {
  background: linear-gradient(135deg, #f5f5ff, #ffffff);
}

.item-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
  align-items: center;
}

.item-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #6666ff;
}

.item-cost {
  font-size: 28rpx;
  color: #ff6699;
  font-weight: bold;
}

.item-details {
  margin-bottom: 20rpx;
}

.item-details text {
  display: block;
  font-size: 26rpx;
  color: #888;
  margin-bottom: 8rpx;
}

.item-actions {
  display: flex;
  justify-content: flex-end;
}
</style>
